package order

import (
	"context"
	"fmt"
	"service/api/api"
	mBase "service/model/crm_base"
	model "service/model/crm_order"
	mCache "service/model/hr_cache"
	"time"

	gpc "gitee.com/cloudapex/protos/comm/pb"
	baseGpb "gitee.com/cloudapex/protos/crm_base/pb"
	gpb "gitee.com/cloudapex/protos/crm_order/pb"
	gpa "gitee.com/cloudapex/protos/hr_cache/pb"

	"service/model/mod"

	"gitee.com/cloudapex/ulern/htp"
	"gitee.com/cloudapex/ulern/util"
	"github.com/gin-gonic/gin"
)

/*
 * 描述: 临时开课审核列表
 * 路由: /order/tmpClsList
 * 方法: GET
 *********************************************************************/
type TmpClsList struct {
	mod.SortFinder // 1:下单金额 2:下单时间 3:审核时间 4:关课时间
	mod.PageFinder

	CsId    int64  `form:"csId" json:"csId" binding:"omitempty"`       // 客户Id
	OrderId string `form:"orderId" json:"orderId" binding:"omitempty"` // 订单号
	Phone   string `form:"phone" json:"phone" binding:"omitempty"`     // 手机号
	UserId  int64  `form:"userId" json:"userId" binding:"omitempty"`   // 下单坐席Id
	ProjId  int64  `form:"projId" json:"projId" binding:"omitempty"`   // 项目Id

	OrderBgn int64 `form:"orderBgn" json:"orderBgn" binding:"omitempty"` // 下单时间(int)
	OrderEnd int64 `form:"orderEnd" json:"orderEnd" binding:"omitempty"` // 下单时间(int)

	State int32 `form:"state" json:"state" binding:"required,min=1,max=3"` // 订单状态(1 未审核 2 已审核 3 已关课)
}
type tmpClsRspItem struct {
	OrderId    int64                        `json:"orderId"`    // 订单ID
	CommpId    int64                        `json:"commpId"`    // 公司ID
	Phone      string                       `json:"phone"`      // 手机号
	BillNo     string                       `json:"billNo"`     // 订单单号
	BillType   int64                        `json:"billType"`   // 单号类型  1 全款 2 尾款 3 定金
	CustomerId int64                        `json:"customerId"` // 客户ID
	PlaceId    int64                        `json:"placeId"`    // 下单人
	PlaceName  string                       `json:"placeName"`  // 下单人_
	UserId     int64                        `json:"userId"`     // 成单坐席
	ShowId     uint64                       `json:"showId"`     // 所属组织ID
	ShowIdStr  string                       `json:"showIdStr"`  // 所属组织ID string
	RoleId     int64                        `json:"roleId"`     // 所属角色ID
	Examine    int64                        `json:"examine"`    // 审核类型 1 自动审核 2 手动审核
	TotalPrice int64                        `json:"totalPrice"` // 实际支付价格
	OrderType  int64                        `json:"orderType"`  // 订单类型 1 网课  2 学历  3 证书 4 代报名 5其他待定
	Notes      string                       `json:"notes"`      // 订单通用备注
	CreatedAt  int64                        `json:"createdAt"`  // 订单下单时间
	PayAt      int64                        `json:"payAt"`      // 订单支付时间
	Status     int64                        `json:"status"`     // 订单状态  1 未支付  2 已支付  3 已分配 4 已驳回 5手动取消 6自动取消
	Details    []*model.CrmOrderInfo        `json:"details"`    // 订单下的网课详情
	PayType    int64                        `json:"payType"`    // 支付方式
	TeachId    int64                        `json:"teachId"`    // 班主任ID
	CancelAt   int64                        `json:"cancelAt"`   // 订单取消时间
	ReasonAt   int64                        `json:"reasonAt"`   // 订单驳回时间
	Reason     string                       `json:"reason"`     // 订单驳回原因
	AdminId    int64                        `json:"adminId"`    // 审核人
	DistrId    int64                        `json:"distrId"`    // 分配人
	DistrAt    int64                        `json:"distrAt"`    // 分配时间
	Temporary  *model.CrmTemporaryOrderInfo `json:"temporary"`  // 临时开课详情
}

func (this *TmpClsList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	rsp, err := model.Order.CrmTemporaryOrderList(ctx, &gpb.CrmTemporaryOrderListReq{
		Pager: &gpc.PageResponse{
			Page:  int64(this.PageFinder.Page),
			Count: int64(this.PageFinder.Pnum),
			Order: int64(this.SortFinder.Order),
			Orule: int64(this.SortFinder.Orule + 1),
		},

		CommpId:    user.CId,
		UserId:     this.UserId,
		ShowId:     user.ShowId,
		CustomerId: uint64(this.CsId),
		BillNo:     this.OrderId,
		Phone:      this.Phone,
		ProjectId:  this.ProjId,
		OrderBgn:   this.OrderBgn,
		OrderEnd:   this.OrderEnd,
		State:      int64(this.State),
	})
	if err != nil {
		return htp.RespModelErr("_t", err)
	}

	items := []*tmpClsRspItem{}
	if err := util.Convert(&items, rsp.Data); err != nil {
		return htp.RespConvertErr("", err)
	}
	if resp := this.HandleRespItems(c, ctx, items); resp.Err() != nil {
		return resp
	}

	for _, item := range items {
		item.ShowIdStr = fmt.Sprintf("%d", item.ShowId)
	}

	return htp.RespOK("", &struct {
		Total int32       `json:"total"`
		List  interface{} `json:"list"`
	}{int32(rsp.Pager.Total), items})
}
func (this *TmpClsList) HandleRespItems(c *gin.Context, ctx context.Context, items []*tmpClsRspItem) htp.Response {
	user := mod.CurrUser(c)
	if len(items) == 0 {
		return htp.RespOK("", nil)
	}

	uIds := []int64{}
	for _, it := range items {
		// uint
		it.Temporary.ShowIdStr = it.Temporary.ShowId

		it.Temporary.Status = int64(this.State) // 回填 state
		uIds = append(uIds, it.PlaceId)
	}

	uIds = util.RemoveDuplicate64(uIds)
	rspNameList, err := mCache.UserCacheServer.UserNameList(ctx, &gpa.UserLoginReqIdsReq{CId: user.CId, Ids: uIds})
	if err != nil {
		return htp.RespModelErr("_u", err)
	}

	mapNames := map[int64]string{}
	for _, it := range rspNameList.NameList {
		mapNames[it.Id] = it.Name
	}

	for _, it := range items {
		it.PlaceName = mapNames[it.PlaceId]
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 临时开课
 * 路由: /order/temporary
 * 方法: POST
 *********************************************************************/
type Temporary struct {
	OrderId int64 `form:"orderId" json:"orderId" binding:"required"` // 订单Id
}

func (this *Temporary) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	_, err := model.Order.CrmTemporaryOrderCreate(ctx, &gpb.CrmTemporaryOrderCreateReq{
		OrderId: this.OrderId,
		UserId:  user.UId,
		ShowId:  mod.SectionMaxLv(user.ShowId),
		Status:  1, // 未审核
	})

	if err != nil {
		return htp.RespModelErr("_t", err)
	}

	return htp.RespOK("", nil)
}

/*
 * 描述: 通过(临时开课审核)
 * 路由: /order/pass
 * 方法: POST
 *********************************************************************/
type Pass struct {
	OrderId  int64   `form:"orderId" json:"orderId" binding:"required"`   // 订单Id
	Phone    string  `form:"phone" json:"phone" binding:"required"`       // 手机号
	ClassIds []int64 `form:"classIds" json:"classIds" binding:"required"` // 班型Id
}

func (this *Pass) Handle(c *gin.Context, ctx context.Context) htp.Response {
	//user := mod.CurrUser(c)

	_, err := model.Order.CrmTemporaryOrderStatus(ctx, &gpb.CrmTemporaryOrderStatusReq{
		OrderId:   this.OrderId,
		ExamineAt: time.Now().Unix(),
		Status:    2, // 已审核
		CloseAt:   time.Now().Add(mod.TMP_CLS_DURATION).Unix(),
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	api.ClassOpen(ctx, this.Phone, time.Now().Add(mod.TMP_CLS_DURATION).Unix(), this.ClassIds)

	return htp.RespOK("", nil)
}

/*
 * 描述: 取消订单
 * 路由: /order/cancel
 * 方法: POST
 *********************************************************************/
type Cancel struct {
	OrderId int64 `form:"orderId" json:"orderId" binding:"required"` //订单ID
}

func (this *Cancel) Handle(c *gin.Context, ctx context.Context) htp.Response {
	_, err := model.Order.CrmOrderStatus(ctx, &gpb.CrmOrderStatusReq{
		OrderId:  this.OrderId,
		CancelAt: time.Now().Unix(),
		Status:   int64(mod.EOrderS_HandCancel),
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 续课(已支付的订单)
 * 路由: /order/continue
 * 方法: POST
 *********************************************************************/
type Continue struct {
}

func (this *Continue) Handle(c *gin.Context, ctx context.Context) htp.Response {
	return htp.RespOK("", nil)
}

/*
 * 描述: 审核(未支付的)
 * 路由: /order/check
 * 方法: POST
 *********************************************************************/
type Check struct {
	OrderId int64 `form:"orderId" json:"orderId" binding:"required"` // 订单ID
}

func (this *Check) Handle(c *gin.Context, ctx context.Context) htp.Response {

	currentUser := mod.CurrUser(c)

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	in := &gpb.CrmOrderGetReq{
		OrderId: this.OrderId,
	}
	res, err := model.Order.GetOrderInfo(ctx, in)

	util.Debug("%s", res)

	var senior, low OrAgreeType

	if err != nil {
		util.Debug("%s", err)
		return htp.RespModelErr("", err)
	}
	if res.OrderId == 0 {
		util.Debug("该订单不存在")
		util.Debug("%s", res)

		return htp.RespErr(2, "该订单不存在", nil)
	}

	if res.Status != 1 {
		util.Debug("账单状态不正确")
		return htp.RespErr(3, "账单状态不正确", err)
	}

	req := &gpa.LoginCacheReq{
		Id: res.UserId,
	}
	userInfo, err := mCache.UserCacheServer.GetAllLoginCache(ctx, req)
	util.Debug("%s", userInfo)

	if err != nil {
		util.Debug("%s", err)
		return htp.RespModelErr("", err)
	}

	util.Debug("%s", res.Details)

	var isSenior int64 = 1

	if len(res.Details) == 0 {
		return htp.RespErr(1, "订单数据异常", nil)
	}

	if res.OrderType == 1 {

		for i, v := range res.Details {

			classInfo, err := GetClassInfo(ctx, v.ClassId)
			if err != nil {
				util.Debug("%s", err)
				return htp.RespModelErr("", err)
			}

			if classInfo.UpgRade == 1 {
				isSenior = 2
			}

			util.Debug("%s", classInfo)
			if re, tids := IsNeedSign(classInfo, ctx); re {
				if classInfo.UpgRade == 1 {
					senior.Type = 2
					senior = AgreeUpdate(senior, tids, i, res.Details)
				} else {
					low.Type = 1
					low = AgreeUpdate(low, tids, i, res.Details)
				}
			}

			if res.BillType != 3 {

				userreq := &gpb.UserClassReq{
					UserClass: &gpb.UserClass{
						CId:     v.ClassId,
						OrderNo: res.BillNo,
					},
				}

				userres, _ := model.UserClass.GetUserClass(ctx, userreq)
				if userres.UserClass.Id == 0 {
					userreq := &gpb.UserClassReq{
						UserClass: &gpb.UserClass{
							Phone:     res.Phone,
							CId:       v.ClassId,
							CName:     v.ClassName,
							OrderNo:   res.BillNo,
							RealPrice: int64(v.Price),
							At:        time.Now().Unix(),
							CloseAt:   time.Now().AddDate(0, int(classInfo.ValidTeam), 0).Unix(),
							State:     0,
						},
					}
					_, err := model.UserClass.AddUserClass(ctx, userreq)
					if err != nil {
						return htp.RespModelErr("", err)
					}

				} else {

					userreq := &gpb.UserClassReq{
						UserClass: &gpb.UserClass{
							Id:      userres.UserClass.Id,
							CloseAt: time.Now().AddDate(0, int(classInfo.ValidTeam), 0).Unix(),
						},
					}

					_, err := model.UserClass.EditUserClass(ctx, userreq)
					if err != nil {
						return htp.RespModelErr("", err)
					}
				}
			}

		}
	}

	//开通学员账号
	infoReq := &gpb.AccountGetReq{
		Phone: res.Phone,
	}
	infoRes, err := model.StudentInfo.StudentAccountGet(ctx, infoReq)

	util.Debug("%s", infoRes)

	if err != nil {
		util.Debug("%s", err)
		return htp.RespModelErr("", err)
	}
	if infoRes.StudentId == 0 {
		accountReq := &gpb.AccountCreateReq{
			Phone:   res.Phone,
			Pass:    util.MD5s(res.Phone),
			Email:   "",
			Address: "",
		}
		model.StudentInfo.StudentAccountCreate(ctx, accountReq)

		util.Debug("开通学员账号成功")
	}

	//统计下单金额  和 下单数量
	if res.TotalPrice > 0 {

		if res.BillType < 3 {
			statistic := &gpb.OrderStatisticsReq{
				CommpId:    res.CommpId,
				Count:      1,
				TotalPrice: res.TotalPrice,
			}
			model.Order.CrmOrderStatistic(ctx, statistic)
			util.Debug("非定金统计金额")

		} else {
			statistic := &gpb.OrderStatisticsReq{
				CommpId:    res.CommpId,
				Count:      0,
				TotalPrice: res.TotalPrice,
			}
			model.Order.CrmOrderStatistic(ctx, statistic)
			util.Debug("定金统计金额")
		}
	}

	//订单更新
	updateReq := &gpb.CrmOrderStatusReq{
		OrderId: res.OrderId,
		PayAt:   time.Now().Unix(),
		PayType: int64(mod.EPayW_Other),
		AdminId: currentUser.UId,
		Examine: int64(mod.ECheckW_Hand),
	}

	//updateReq.Status = 2
	////招生
	//if res.RoleId == 1 {
	//
	//	util.Debug("招生进入")
	//	if res.OrderType == 1 {
	//
	//		//班主任的话，直接将学员分配给自己
	//		stuReq := &gpb.StudentOrderGetReq{
	//			Phone: res.Phone,
	//		}
	//		stuRes, err := model.StudentOrder.StudentOrderGet(ctx, stuReq)
	//		if err != nil {
	//			util.Debug("%s", err)
	//			return htp.RespModelErr("", err)
	//		}
	//		util.Debug("班主任学员库信息：%s", stuRes)
	//
	//		if stuRes.CustomerId != 0 {
	//
	//			changeOrder := &gpb.StudentOrderStatusReq{
	//				Phone:  res.Phone,
	//				Amount: res.TotalPrice + stuRes.Amount,
	//			}
	//
	//			if stuRes.Senior != 2 && isSenior == 2 && res.BillType != 3 {
	//				changeOrder.Senior = isSenior
	//			}
	//
	//			_, err = model.StudentOrder.StudentOrderStatus(ctx, changeOrder)
	//			if err != nil {
	//				util.Debug("更新学员库成交金额失败：%s", err)
	//				return htp.RespModelErr("", err)
	//			}
	//
	//			if res.BillType != 3 {
	//
	//				updateReq.TeachId = int64(stuRes.UserId)
	//				err = AddAutoAssignLog(ctx, res.CommpId, res.OrderId, int64(stuRes.UserId), stuRes.UserName)
	//				if err != nil {
	//					util.Debug("添加分配记录失败：%s", err)
	//				}
	//				updateReq.Status = 3
	//			}
	//
	//		}
	//	}
	//
	//} else if res.RoleId == 2 {
	//
	//	util.Debug("班主任进入")
	//	if res.OrderType == 1 {
	//		//班主任的话，直接将学员分配给自己
	//		stuReq := &gpb.StudentOrderGetReq{
	//			Phone: res.Phone,
	//		}
	//		stuRes, err := model.StudentOrder.StudentOrderGet(ctx, stuReq)
	//		if err != nil {
	//			util.Debug("%s", err)
	//			return htp.RespModelErr("", err)
	//		}
	//		util.Debug("班主任学员库信息：%s", stuRes)
	//
	//		if stuRes.CustomerId == 0 {
	//
	//			if res.BillType != 3 {
	//
	//				createReq := &gpb.StudentCreateReq{
	//					CommpId:    res.CommpId,
	//					Phone:      res.Phone,
	//					CustomerId: uint64(res.CustomerId),
	//					Amount:     res.TotalPrice,
	//					UserId:     res.UserId,
	//					UserName:   userInfo.UserInfo.Name,
	//					Senior:     isSenior,
	//					//ProjectId:  rsp.BasePool[0].BaseProject.PId,
	//				}
	//				_, err := model.StudentOrder.StudentOrderCreate(ctx, createReq)
	//				if err != nil {
	//					util.Debug("%s", err)
	//					return htp.RespModelErr("", err)
	//				}
	//
	//				err = AddAutoAssignLog(ctx, res.CommpId, res.OrderId, res.UserId, userInfo.UserInfo.Name)
	//				if err != nil {
	//					util.Debug("添加分配记录失败：%s", err)
	//				}
	//
	//				_, err = mBase.Work.DelWorkPool(ctx, &gpc.BaseReq{Id: uint64(res.CustomerId)})
	//				if err != nil {
	//					util.Debug("删除工作池失败：%s", err)
	//					return htp.RespModelErr("", err)
	//				}
	//				updateReq.TeachId = res.UserId
	//				updateReq.Status = 3
	//			}
	//
	//		} else {
	//
	//			changeOrder := &gpb.StudentOrderStatusReq{
	//				Phone:  res.Phone,
	//				Amount: res.TotalPrice + stuRes.Amount,
	//			}
	//
	//			if stuRes.Senior != 2 && isSenior == 2 && res.BillType != 3 {
	//				changeOrder.Senior = isSenior
	//			}
	//
	//			_, err = model.StudentOrder.StudentOrderStatus(ctx, changeOrder)
	//			if err != nil {
	//				util.Debug("更新学员库成交金额失败：%s", err)
	//				return htp.RespModelErr("", err)
	//			}
	//			if res.BillType != 3 {
	//				updateReq.TeachId = int64(stuRes.UserId)
	//				err = AddAutoAssignLog(ctx, res.CommpId, res.OrderId, int64(stuRes.UserId), stuRes.UserName)
	//				if err != nil {
	//					util.Debug("添加分配记录失败：%s", err)
	//				}
	//				updateReq.Status = 3
	//			}
	//		}
	//
	//	}
	//}

	err = AssignTeacherAndUpdateOrder(ctx, res, updateReq, isSenior, userInfo)

	//_, err = model.Order.CrmOrderUpdate(ctx, updateReq)
	if err != nil {
		util.Debug("更新订单状态失败：%s", err)
		return htp.RespModelErr("", err)
	}
	util.Debug("更新订单状态")

	if res.BillType == 2 {
		endReq := &gpb.CrmOrderGetReq{
			BillNo: res.BillNo,
		}
		_, err = model.Order.CrmDepositOrderEnded(ctx, endReq)
		if err != nil {
			util.Debug("更新子订单状态失败：%s", err)
			return htp.RespModelErr("", err)
		}
	}

	isNeed, _ := OrderIsNeedSign(res.BillNo, ctx)

	util.Debug("%v", isNeed)

	util.Debug("%v %v", senior, low)

	if res.BillType != 3 && isNeed {
		if senior.Pidstr != "" {
			_, err := saveAgree(senior, res, infoRes, ctx)
			if err != nil {
				util.Debug("订单协议出现错误：")
				util.Debug("%s", err)
				return htp.RespModelErr("", err)
			}
		}

		if low.Pidstr != "" {
			_, err := saveAgree(low, res, infoRes, ctx)
			if err != nil {
				fmt.Println("订单协议出现错误：")
				util.Debug("订单协议出现错误：")
				util.Debug("%s", err)
				return htp.RespModelErr("", err)

			}
		}
	}

	//更新库存状态
	logicReq := &baseGpb.PoolLogicReq{
		Id:    uint64(res.CustomerId),
		Logic: 5,
	}
	_, err = mBase.Base.SetPoolLogic(ctx, logicReq)
	if err != nil {
		util.Debug("%s", err)
		return htp.RespModelErr("", err)
	}

	return htp.RespOK("", nil)
}

/*
 * 描述: 驳回(未支付的)
 * 路由: /order/reject
 * 方法: POST
 *********************************************************************/
type Reject struct {
	OrderId int64  `form:"orderId" json:"orderId" binding:"required"` // 订单ID
	Reason  string `form:"reason" json:"reason" binding:"omitempty"`  // 驳回备注
}

func (this *Reject) Handle(c *gin.Context, ctx context.Context) htp.Response {
	_, err := model.Order.CrmOrderStatus(ctx, &gpb.CrmOrderStatusReq{
		OrderId:  this.OrderId,
		ReasonAt: time.Now().Unix(),
		Reason:   this.Reason,
		Status:   int64(mod.EOrderS_Reject),
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 分配班主任
 * 路由: /order/assign
 * 方法: POST
 *********************************************************************/
const (
	EAssign_PartErr = 1 // 存在部分错误
)

type AssignOrder struct {
	OrderId    int64  `form:"orderId" json:"orderId" binding:"required"`       // 订单ID
	Phone      string `form:"phone" json:"phone" binding:"required"`           // 手机号
	CustomerId uint64 `form:"customerId" json:"customerId" binding:"required"` // 客户ID
	ProjId     int64  `form:"projId" json:"projId" binding:"required"`         // 项目ID
	ProjName   string `form:"projName" json:"projName" binding:"required"`     // 项目名称
	Amount     int64  `form:"amount" json:"amount" binding:"required"`         // 成交金额
}
type Assign struct {
	UserId   int64         `form:"userId" json:"userId" binding:"required"`     // 班主任坐席ID
	UserName string        `form:"userName" json:"userName" binding:"required"` // 班主任坐席名称
	Orders   []AssignOrder `form:"orders" json:"orders" binding:"required"`     // 列表
}

type PoolRes struct {
	Base mBase.BaseBase    `json:"baseBase"`
	Proj mBase.BaseProject `json:"baseProject"`
	Tg   mBase.BaseProTg   `json:"baseProTg"`
}

func (this *Assign) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)

	type faildItem struct {
		CustomerId uint64 `json:"customerId"` // 客户ID
		ErrorInfo  string `json:"errInfo"`    // 错误原因
	}
	failds := []faildItem{}

	showids, err := GetShowIds(ctx, this.UserId)

	util.Debug("用户的可见区间范围：%s", showids)

	// 取得所有手机号下面的所有订单
	phones := []int64{}
	for _, it := range this.Orders {
		phones = append(phones, int64(util.ConvInt(it.Phone)))
	}
	rsp, err := model.Order.CrmOrderAdminList(ctx, &gpb.CrmOrderListReq{
		Page:        1,
		Count:       1000,
		Order:       1,
		Orule:       1,
		CommpId:     user.CId,
		PhoneArr:    phones,
		BillTypeArr: []int64{int64(mod.EPayT_Full), int64(mod.EPayT_Tail)},
		State:       []int64{int64(mod.EOrderS_Payed)},
	})
	if err != nil {
		return htp.RespModelErr("_o", err)
	}

	this.Orders = []AssignOrder{}
	for _, it := range rsp.Data {
		this.Orders = append(this.Orders, AssignOrder{
			OrderId:    it.OrderId,
			Phone:      it.Phone,
			CustomerId: uint64(it.CustomerId),
			ProjId:     it.Details[0].ProjectId,
			ProjName:   it.Details[0].ProjectName,
			Amount:     it.TotalPrice,
		})
	}

	for _, it := range this.Orders {

		//班主任的话，直接将学员分配给自己
		stuReq := &gpb.StudentOrderGetReq{
			Phone: it.Phone,
		}
		stuRes, err := model.StudentOrder.StudentOrderGet(ctx, stuReq)
		if err != nil {
			util.Debug("获取班主任学员库信息失败：%s", err)
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("分配失败:%s", err.Error())})
			continue
		}
		if stuRes.CustomerId == 0 {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("分配失败:%s", nil)})
			continue
		}

		var bres PoolRes
		rsp1, err := mBase.Base.SelectPool(ctx, &baseGpb.BasePoolReq{
			BasePool: &baseGpb.BasePool{
				BaseBase: &baseGpb.BaseBase{},
				BaseProject: &baseGpb.BaseProject{
					Id: it.CustomerId,
				},
				BaseProTg: &baseGpb.BaseProTg{},
			},
		})
		if err != nil {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("分配班主任失败:%s", err.Error())})
			continue
		}

		if err := util.Convert(&bres, rsp1.BasePool); err != nil {
			return htp.RespConvertErr("", err)
		}

		//是否可分配班主任
		//数据是否再 用户的可见区间， 用户是否
		bl := IsGet(showids, bres.Proj.StationShow)
		if !bl {
			util.Debug("可见范围判断失败%s", bl)
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("分配班主任失败:%s", nil)})
			continue
		}

		changeOrder := &gpb.StudentOrderStatusReq{
			Phone:     it.Phone,
			Amount:    stuRes.Amount,
			DistrName: this.UserName,
			DistrId:   this.UserId,
			DistrAt:   time.Now().Unix(),
		}

		_, err = model.StudentOrder.StudentOrderStatus(ctx, changeOrder)
		if err != nil {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("分配失败:%s", err.Error())})
			continue
		}

		// 更新订单状态
		_, err = model.Order.CrmOrderStatus(ctx, &gpb.CrmOrderStatusReq{
			OrderId: it.OrderId,
			TeachId: this.UserId,
			DistrId: user.CId,
			DistrAt: time.Now().Unix(),
			Status:  int64(mod.EOrderS_Assign),
		})
		if err != nil {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("订单状态:%s", err.Error())})
			continue
		}

		// 更改机会所属班主任
		_, err = mBase.Base.EditPool(ctx, &baseGpb.BasePoolReq{
			BasePool: &baseGpb.BasePool{
				BaseBase: &baseGpb.BaseBase{},
				BaseProject: &baseGpb.BaseProject{
					Id:     it.CustomerId,
					UId:    this.UserId,
					ShowId: mod.Min(showids),
				},
				BaseProTg: &baseGpb.BaseProTg{},
			},
		})
		if err != nil {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("机会变更坐席:%s", err.Error())})
			continue
		}

		// 删除工作池
		_, err = mBase.Work.DelWorkPool(ctx, &gpc.BaseReq{Id: it.CustomerId})
		if err != nil {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("删除工作池:%s", err.Error())})
			continue
		}

		// 分配记录
		_, err = model.Order.CrmOrderLogCreate(ctx, &gpb.CrmOrderLogReq{
			CommpId:   user.CId,
			OrderId:   it.OrderId,
			UserId:    this.UserId,
			UserName:  this.UserName,
			RoleId:    user.RoleId,
			AdminId:   user.UId,
			AdminName: user.Name,
			Status:    int64(mod.EOrderL_Assign),
		})
		if err != nil {
			failds = append(failds, faildItem{it.CustomerId, fmt.Sprintf("记录失败:%s", err.Error())})
			continue
		}
	}
	if len(failds) > 0 {
		return htp.RespErrData(EAssign_PartErr, "部分操作失败", nil, &struct {
			List interface{} `json:"list"`
		}{failds})
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 业绩指派
 * 路由: /order/appoint
 * 方法: POST
 *********************************************************************/
type Appoint struct {
	OrderId int64 `form:"orderId" json:"orderId" binding:"required"` // 订单ID
	UserId  int64 `form:"userId" json:"userId" binding:"required"`   // 给坐席ID
}

func (this *Appoint) Handle(c *gin.Context, ctx context.Context) htp.Response {
	//user := mod.CurrUser(c)

	_, err := model.Order.CrmOrderStatus(ctx, &gpb.CrmOrderStatusReq{
		OrderId: this.OrderId,
		UserId:  this.UserId,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 分配记录
 * 路由: /order/assignLog
 * 方法: GET
 *********************************************************************/
type AssignLog struct {
	OrderId int64 `form:"orderId" json:"orderId" binding:"required"` // 订单ID
}
type assignLogItem struct {
	UserId    int64  `json:"userId"`    // 用户ID
	UserName  string `json:"userName"`  // 用户名称
	AdminId   int64  `json:"adminId"`   // 操作人ID
	AdminName string `json:"adminName"` // 操作人名称
	CreateAt  int64  `json:"createAt"`  // 记录时间
}

func (this *AssignLog) Handle(c *gin.Context, ctx context.Context) htp.Response {
	rsp, err := model.Order.CrmOrderLogList(ctx, &gpb.CrmOrderLogListReq{
		Pager: &gpc.PageResponse{
			Page:  1,
			Count: 1000,
			Order: 1,
			Orule: 1,
		},
		OrderId: this.OrderId,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	items := []*assignLogItem{}
	if err := util.Convert(&items, rsp.Data); err != nil {
		return htp.RespConvertErr("", err)
	}

	return htp.RespOK("", &struct {
		Total int32       `json:"total"`
		List  interface{} `json:"list"`
	}{int32(rsp.Pager.Total), items})
}
